package cn.gzjp.modules.it.api.web;

import cn.gzjp.common.config.ConfigUtils;
import cn.gzjp.common.utils.*;
import cn.gzjp.common.web.BaseController;
import cn.gzjp.modules.gas.service.AliyunSms;
import cn.gzjp.modules.it.api.bean.CarPreVo;
import cn.gzjp.modules.it.api.bean.CommonJson;
import cn.gzjp.modules.it.api.bean.WzQueryJson;
import cn.gzjp.modules.it.entity.Car;
import cn.gzjp.modules.it.entity.Member;
import cn.gzjp.modules.it.entity.PlateData;
import cn.gzjp.modules.it.entity.WzLog;
import cn.gzjp.modules.it.service.*;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.aliyuncs.exceptions.ClientException;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 车辆违章查询
 */
@Controller("frontWz")
@Api(value = "违章处理", description = "违章处理")
@RequestMapping(value = "${frontPath}/wz")
public class WzController extends BaseController implements Serializable {

	@Autowired
	private WzLogService wzLogService;
	@Autowired
	private CarService carService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private PlateDataService plateDataService;
	
	public static final String APPKEY = "9783aeb09bc69afca94d9f0b7f4bf854";

	/**
	 * 违章查询
	 * @param chepai 车牌
	 * @param engineNO 发动机号
	 * @param carVIN 车架号
	 * @return
	 */
	@ApiOperation(value = "违章查询")
	@RequestMapping(value = "query", method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="chepai",value="车牌",dataType="String",paramType="form",required =true),
		@ApiImplicitParam(name="engineNO",value="发动机号",dataType="String",paramType="form",required =true),
		@ApiImplicitParam(name="carVIN",value="车架号",dataType="String",paramType="form",required =true),
		@ApiImplicitParam(name="openid",value="openid",dataType="String",paramType="form",required =true),
		@ApiImplicitParam(name="mobile",value="手机号",dataType="String",paramType="form",required =true),
		@ApiImplicitParam(name="address",value="地址",dataType="String",paramType="form")
      })
	
	@ResponseBody
	public String wzQuery(String chepai, String engineNO, String carVIN,String openid,String mobile,String address) {
		WzQueryJson result = new WzQueryJson();
		log.info("车牌 chepai=" + chepai);
		log.info("发动机号 engineNO=" + engineNO);
		log.info("车架号 carVIN=" + carVIN);
		log.info("openid=" + openid);
		log.info("mobile=" + mobile);
		log.info("address=" + address);
		if (StringUtils.isBlank(chepai)) {
			result.setMsg("请输入车牌");
			result.setCode(1);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		if (StringUtils.isBlank(carVIN)) {
			result.setMsg("请输入车架号");
			result.setCode(1);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		if (StringUtils.isBlank(mobile)) {
			result.setMsg("请输入手机号");
			result.setCode(1);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		if (chepai.length() < 7 ) {
			result.setMsg("车牌长度不正确");
			result.setCode(1);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		
		if("undefined".equals(openid)||"undefined".equals(chepai)||"undefined".equals(carVIN)){
    		result.setMsg("网络错误，请刷新后重试");
			result.setCode(1);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
    	}
		if("null".equals(engineNO)||StringUtils.isBlank(engineNO)){
			engineNO="000000";
		}
		Member member = memberService.get(openid);
		if(member!=null&&StringUtils.isBlank(member.getMobile())&&mobile.length()==11){//更新用户手机号
			member.setMobile(mobile);
			memberService.save(member);
		}
		Car car = carService.get(chepai);
		if(car==null||StringUtils.isBlank(car.getEngineNeed())||StringUtils.isBlank(car.getClassaNeed())){
			String url = "http://v.juhe.cn/wz/carPre";// 请求接口地址
			Map<String, String> params = new HashMap<String, String>();// 请求参数
			params.put("dtype", "json");// 返回数据格式：json或xml或jsonp,默认json
			params.put("callback", "");// 返回格式选择jsonp时，必须传递
			params.put("key", APPKEY);// 你申请的key
			params.put("hphm", chepai);// 号牌号码 完整7位 ,需要utf8 urlencode*
			String cityCode = "";
			String city="";
			String province="";
			String engine;//是否需要发动机号0:不需要 1:需要
			String engineNO_2;//	需要几位发动机号0:全部 1-9 :需要发动机号后N位;
			String classa;  //是否需要车架号0,不需要 1,需要
			String classno_2;   //需要几位车架号0:全部 1-9: 需要车架号后N位
			try {
				String content = JuheService.net(url, params, "GET");
				JSONObject object = new JSONObject(content); // JSONObject.fromObject(result);
				if (object.getInt("error_code") == 0) {
					JSONObject resultJson = object.getJSONObject("result");
					province = resultJson.get("province").toString();
					city = resultJson.get("city_name").toString();
					cityCode = resultJson.get("city_code").toString();
					engine = resultJson.get("engine").toString();
					engineNO_2 = resultJson.get("engineno").toString();
					classa = resultJson.get("classa").toString();
					classno_2 = resultJson.get("classno").toString();
					
					String  engine0Province = ConfigUtils.getProperty("engine0Province");
					log.info("engine0Province="+engine0Province);
					String chepaiProvince = chepai.substring(0,1);
					log.info("chepaiProvince="+chepaiProvince);
					String plate = chepai.substring(0,2);
					PlateData pdata = plateDataService.get(plate);
					String wzstatus="1";
					if(pdata!=null){
						wzstatus = pdata.getWzstatus();
					}
					log.info("wzstatus="+wzstatus);
					
					if(engine0Province.contains(chepaiProvince)||"1".equals(wzstatus)){
						engine="0";
						engineNO_2="0";
					}
					
					if(car==null){
						car = new Car();
						car.setId(chepai);
					}
					car.setProvince(province);
					car.setCity(city);
					car.setCityCode(cityCode);
					car.setEngineNeed(engine);
					car.setEngineNumber(engineNO_2);
					car.setClassaNeed(classa);
					car.setClassaNumber(classno_2);
					carService.save(car);//保存更新车辆
				} else {
					System.out.println(object.get("error_code") + ":" + object.get("reason"));
					result.setMsg(object.get("error_code") + ":" + object.get("reason"));
					result.setCode(3);
					log.info("返回给小程序数据:"+this.mapper.toJson(result));
					return this.mapper.toJson(result);
				}
			} catch (Exception e) {
				result.setMsg("获取车牌"+chepai+"省市数据出错");
				result.setCode(3);
				log.info("返回给小程序数据:"+this.mapper.toJson(result));
				return this.mapper.toJson(result);
			}
		}
		
//		Car car = carService.get(chepai);
//		if(car==null){
//			result.setMsg("请先调用api/wz/wzPre接口获取违章所需参数");
//			result.setCode(2);
//			log.info("返回给小程序数据:"+this.mapper.toJson(result));
//			return this.mapper.toJson(result);
//		}
//		if(StringUtils.isBlank(car.getCityCode())||StringUtils.isBlank(car.getEngineNeed())||StringUtils.isBlank(car.getEngineNumber())||StringUtils.isBlank(car.getClassaNeed())||StringUtils.isBlank(car.getClassaNumber())){
//			result.setMsg("请先调用api/wz/wzPre接口获取违章所需参数");
//			result.setCode(2);
//			log.info("返回给小程序数据:"+this.mapper.toJson(result));
//			return this.mapper.toJson(result);
//		}
		result.setProvince(car.getProvince());
		result.setCity(car.getCity());
		
		String haveWz = (String) CacheUtils.get(chepai);
		log.info("缓存中记录haveWz="+haveWz);
		if("no".equals(haveWz)){
			log.info("缓存中读取没有违章记录");
			result.setIllegal(0);
			result.setUntreated(0);
			result.setPoints(0);
			result.setFine(0);
			result.setCode(-1);//没有违章记录
			result.setMsg("没有查询到违章记录");//没有违章记录
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		String engineNO2 = engineNO;
		String carVIN2 = carVIN;
		if("1".equals(car.getEngineNeed())){//需要发动机号
			String engineNunber = car.getEngineNumber();
			int number = engineNO.length()-Integer.parseInt(engineNunber);
			if(number<0||StringUtils.isBlank(engineNO)){
				String plate = chepai.substring(0,2);
				PlateData pdata = plateDataService.get(plate);
				pdata.setWzstatus("3");
				plateDataService.save(pdata);
				log.info("更新wzstatus状态为3");
				result.setMsg("发动机号错误，请输入发动机号后"+engineNunber+"位");
				result.setCode(3);
				log.info("返回给小程序数据:"+this.mapper.toJson(result));
				return this.mapper.toJson(result);
			}
			if(!"0".equals(car.getEngineNumber())&&number>=0){//需要发动机位数 0是全部不截取
				engineNO2 = engineNO.substring(number, engineNO.length());
			}
		}
		if("1".equals(car.getClassaNeed())){//需要车架号
			String classaNunber = car.getClassaNumber();
			int number = carVIN.length() - Integer.parseInt(classaNunber);
			if(number<0||StringUtils.isBlank(carVIN)){
				result.setMsg("车架号错误，请输入车架号后"+classaNunber+"位");
				result.setCode(3);
				log.info("返回给小程序数据:"+this.mapper.toJson(result));
				return this.mapper.toJson(result);
			}
			if(!"0".equals(car.getClassaNumber())&&number>=0){//需要车架号位数 0是全部不截取
				carVIN2 = carVIN.substring(number, carVIN.length());
			}
		}
		WzLog search = new WzLog();
		search.setLicensePlate(chepai);
		List<WzLog> wzInfoList = wzLogService.findList(search);
		log.info("数据库中读取记录 wzInfoList=" + wzInfoList);
		boolean searchForApi = (!"no".equals(haveWz))&&(wzInfoList == null || wzInfoList.size() == 0);
		log.info("是否要调用违章查询接口 searchForApi=" + searchForApi);
		if (searchForApi) {//通过接口去查询了啊
			log.info("无缓存、数据库里也无违章记录、通过接口查询开始");
			log.info("截取后的发动机号 engineNO2="+engineNO2);
			log.info("截取后的车架号 carVIN2="+carVIN2);
			String url = "http://v.juhe.cn/wz/query";// 请求接口地址
			Map<String,String> params = new HashMap<String, String>();// 请求参数
			params.put("dtype", "json");// 返回数据格式：json或xml或jsonp,默认json
			params.put("callback", "");// 返回格式选择jsonp时，必须传递
			params.put("key", APPKEY);// 你申请的key
			params.put("hphm", chepai);// 号牌号码 完整7位 ,需要utf8 urlencode*
			params = new HashMap<String, String>();// 请求参数
			params.put("dtype", "json");// 返回数据格式：json或xml或jsonp,默认json
			params.put("callback", "");// 返回格式选择jsonp时，必须传递
			params.put("key", APPKEY);// 你申请的key
			params.put("city", car.getCityCode());// 城市代码 *
			params.put("hphm", chepai);// 号牌号码 完整7位 ,需要utf8 urlencode*
			params.put("hpzl", "02");// 号牌类型，默认02
			params.put("engineno", engineNO2);// 发动机号 (根据城市接口中的参数填写)
			params.put("classno", carVIN2);// 车架号 (根据城市接口中的参数填写)

			try {
				log.info("调用违章接口查询开始");
				String content = JuheService.net(url, params, "GET");
				log.info("调用违章接口获取到的数据"+content);
				JSONObject object = new JSONObject(content); // JSONObject.fromObject(result);
				if (object.getInt("error_code") == 0) {
					JSONObject resultJson = object.getJSONObject("result");
					com.alibaba.fastjson.JSONObject json = JSON.parseObject(resultJson.toString());
					String listsString = json.get("lists").toString();
					wzInfoList = com.alibaba.fastjson.JSON.parseObject(listsString, new TypeReference<List<WzLog>>() {
					});
					result.setWzList(wzInfoList);					//没有异常
					car.setId(chepai);
					car.setMobile(mobile);
					car.setCarVIN(carVIN);
					car.setEngineNO(engineNO);
					carService.save(car,openid);//更新下车的信息
				} else {
					log.info(object.get("error_code") + ":" + object.get("reason"));
					System.out.println(object.get("error_code") + ":" + object.get("reason"));
					result.setMsg(object.get("error_code") + ":" + object.get("reason"));
					if(result.getMsg().startsWith("203611")){
						result.setMsg("查询不到记录，请检查车牌号是否正确");
					}
					result.setCode(3);
					String plate = chepai.substring(0,2);
					PlateData pdata = plateDataService.get(plate);
					pdata.setWzstatus("3");
					plateDataService.save(pdata);
					log.info("更新wzstatus状态为3");
					log.info("返回给小程序数据:"+this.mapper.toJson(result));
					return this.mapper.toJson(result);
				}
			} catch (Exception e) {
				log.info("违章查询接口异常"+e.getMessage());
				result.setMsg("查询异常");
				result.setCode(4);
				e.printStackTrace();
				log.info("返回给小程序数据:"+this.mapper.toJson(result));
				return this.mapper.toJson(result);
			}
		}
		
		if(wzInfoList!=null&&wzInfoList.size()>0){
			result.setIllegal(wzInfoList.size());
			int points=0;
			int fine=0;//罚款
			int untreated=0;//未处理
			for(WzLog info:wzInfoList){
				if(StringUtils.isNotBlank(info.getFen())){
					points+=Integer.parseInt(info.getFen());
				}
				if(StringUtils.isNotBlank(info.getMoney())){
					fine+=Integer.parseInt(info.getMoney());
				}
				info.setLicensePlate(chepai);
				if(StringUtils.isBlank(info.getId())){//新入库
					info.setCreateTime(new Date());
					info.setDealWith("0");
				}
				if("0".equals(info.getDealWith())||"1".equals(info.getDealWith())){
					untreated++;//未处理
				}
				info.setArchiveno(StringUtil.getRandNum(12));//处罚决定书
				wzLogService.save(info);
			}
			car.setMoney(fine);;
        	car.setFen(points);
        	car.setIllegal(wzInfoList.size());
        	car.setUntreated(untreated);
        	car.setCarVIN(carVIN);
			car.setEngineNO(engineNO);
        	carService.save(car);//更新车辆信息	
        	result.setIllegal(wzInfoList.size());
        	result.setPoints(points);
			result.setFine(fine);
			result.setWzList(wzInfoList);
			result.setUntreated(untreated);
			CacheUtils.put(chepai,"yes");
		}else{
			result.setIllegal(0);
			result.setPoints(0);
			result.setFine(0);
			result.setUntreated(0);
			result.setCode(-1);//没有违章记录
			result.setMsg("没有查询到违章记录");//没有违章记录
			CacheUtils.put(chepai,"no");
			log.info("无违章记录,设置到缓存,下次不用调查询接口no");
			car.setMoney(0);;
        	car.setFen(0);
        	car.setIllegal(0);
        	car.setUntreated(0);
        	car.setCarVIN(carVIN);
			car.setEngineNO(engineNO);
        	carService.save(car);//更新车辆信息	
		}
		log.info("返回给小程序数据:"+this.mapper.toJson(result));
		return this.mapper.toJson(result);
	}
	
	
	/**
	 * 违章查询
	 * @param chepai 车牌
	 * @param engineNO 发动机号
	 * @param carVIN 车架号
	 * @return
	 */
	@ApiOperation(value = "违章查询测试专用")
	@RequestMapping(value = "queryTest", method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="chepai",value="车牌",dataType="String",paramType="form",required =true),
		@ApiImplicitParam(name="engineNO",value="发动机号",dataType="String",paramType="form"),
		@ApiImplicitParam(name="carVIN",value="车架号",dataType="String",paramType="form"),
      })
	
	@ResponseBody
	public String wzQueryTest(String chepai, String engineNO, String carVIN) {
		WzQueryJson result = new WzQueryJson();
		if("null".equals(engineNO)||StringUtils.isBlank(engineNO)){
			engineNO="";
		}
		if("null".equals(carVIN)||StringUtils.isBlank(carVIN)){
			carVIN="";
		}
		log.info("违章查询测试专用 车牌 chepai=" + chepai);
		log.info("发动机号 engineNO=" + engineNO);
		log.info("车架号 carVIN=" + carVIN);
		if (StringUtils.isBlank(chepai)) {
			result.setMsg("请输入车牌");
			result.setCode(1);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		if (StringUtils.isBlank(carVIN)) {
			result.setMsg("请输入车架号");
			result.setCode(1);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		
		if (chepai.length() < 7 ) {
			result.setMsg("车牌长度不正确");
			result.setCode(1);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
	
		String engineNO2 = engineNO;
		String carVIN2 = carVIN;
		  List<WzLog> wzInfoList = Lists.newArrayList();
		boolean searchForApi = true;
		log.info("是否要调用违章查询接口 searchForApi=" + searchForApi);
		if (searchForApi) {//通过接口去查询了啊
			log.info("无缓存、数据库里也无违章记录、通过接口查询开始");
			log.info("截取后的发动机号 engineNO2="+engineNO2);
			log.info("截取后的车架号 carVIN2="+carVIN2);
			String url = "http://v.juhe.cn/wz/query";// 请求接口地址
			Map<String,String> params = new HashMap<String, String>();// 请求参数
			params.put("dtype", "json");// 返回数据格式：json或xml或jsonp,默认json
			params.put("callback", "");// 返回格式选择jsonp时，必须传递
			params.put("key", APPKEY);// 你申请的key
			params.put("hphm", chepai);// 号牌号码 完整7位 ,需要utf8 urlencode*
			params = new HashMap<String, String>();// 请求参数
			params.put("dtype", "json");// 返回数据格式：json或xml或jsonp,默认json
			params.put("callback", "");// 返回格式选择jsonp时，必须传递
			params.put("key", APPKEY);// 你申请的key
			params.put("city", "HN_SQ");// 城市代码 *
			params.put("hphm", chepai);// 号牌号码 完整7位 ,需要utf8 urlencode*
			params.put("hpzl", "02");// 号牌类型，默认02
			params.put("engineno", engineNO2);// 发动机号 (根据城市接口中的参数填写)
			params.put("classno", carVIN2);// 车架号 (根据城市接口中的参数填写)
			try {
				log.info("调用违章接口查询开始");
				String content = JuheService.net(url, params, "GET");
				log.info("调用违章接口获取到的数据"+content);
				JSONObject object = new JSONObject(content); // JSONObject.fromObject(result);
				if (object.getInt("error_code") == 0) {
					JSONObject resultJson = object.getJSONObject("result");
					com.alibaba.fastjson.JSONObject json = JSON.parseObject(resultJson.toString());
					String listsString = json.get("lists").toString();
					wzInfoList = com.alibaba.fastjson.JSON.parseObject(listsString, new TypeReference<List<WzLog>>() {
					});
					result.setWzList(wzInfoList);					//没有异常
				} else {
					log.info(object.get("error_code") + ":" + object.get("reason"));
					System.out.println(object.get("error_code") + ":" + object.get("reason"));
					result.setMsg(object.get("error_code") + ":" + object.get("reason"));
					result.setCode(3);
					log.info("返回给小程序数据:"+this.mapper.toJson(result));
					return this.mapper.toJson(result);
				}
			} catch (Exception e) {
				log.info("违章查询接口异常"+e.getMessage());
				result.setMsg("查询异常");
				result.setCode(4);
				e.printStackTrace();
				log.info("返回给小程序数据:"+this.mapper.toJson(result));
				return this.mapper.toJson(result);
			}
		}
		
		if(wzInfoList!=null&&wzInfoList.size()>0){
			result.setIllegal(wzInfoList.size());
			int points=0;
			int fine=0;//罚款
			int untreated=0;//未处理
			for(WzLog info:wzInfoList){
				if(StringUtils.isNotBlank(info.getFen())){
					points+=Integer.parseInt(info.getFen());
				}
				if(StringUtils.isNotBlank(info.getMoney())){
					fine+=Integer.parseInt(info.getMoney());
				}
				info.setLicensePlate(chepai);
				if(StringUtils.isBlank(info.getId())){//新入库
					info.setCreateTime(new Date());
					info.setDealWith("0");
				}
				if("0".equals(info.getDealWith())||"1".equals(info.getDealWith())){
					untreated++;//未处理
				}
			}
		
        	result.setIllegal(wzInfoList.size());
        	result.setPoints(points);
			result.setFine(fine);
			result.setWzList(wzInfoList);
			result.setUntreated(untreated);
		}else{
			result.setIllegal(0);
			result.setPoints(0);
			result.setFine(0);
			result.setUntreated(0);
			result.setCode(-1);//没有违章记录
			result.setMsg("没有查询到违章记录");//没有违章记录
			CacheUtils.put(chepai,"no");
			log.info("无违章记录,设置到缓存,下次不用调查询接口no");
		}
		log.info("返回给小程序数据:"+this.mapper.toJson(result));
		return this.mapper.toJson(result);
	}
	
	
	
	@ApiOperation(value = "违章处理")
	@RequestMapping(value = "dealWith", method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="id",value="违章记录id",dataType="String",paramType="form",required =true),
		@ApiImplicitParam(name="dealWith",value="0未处理1未缴费2已处理",dataType="String",paramType="form",required =true),
		@ApiImplicitParam(name="receiptno",value="回执编号或缴费单号",dataType="String",paramType="form",required =true)
      })
	@ResponseBody
	public String wzDealWith(String id,String dealWith,String receiptno) {
		CommonJson result = new CommonJson();
		log.info("违章处理开始 wzDealWith");
		log.info("id=" + id);
		log.info("dealWith=" + dealWith);
		log.info("receiptno=" + receiptno);
		if (StringUtils.isBlank(id) || StringUtils.isBlank(dealWith)|| StringUtils.isBlank(receiptno)) {
			result.setMsg("参数不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		if("undefined".equals(receiptno)||"undefined".equals(id)||"undefined".equals(dealWith)){
    		result.setMsg("网络错误，请刷新后重试");
			result.setCode(1);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
    	}
		WzLog wzLog = wzLogService.get(id);
		if(wzLog==null){
			result.setCode(-1);
			result.setMsg("没有该违章记录");
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		if("2".equals(dealWith)&&"2".equals(wzLog.getDealWith())){
			result.setCode(2);
			result.setMsg("已处理过的违章无需重复处理");
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		wzLog.setDealWith(dealWith);
		wzLog.setReceiptno(receiptno);
		wzLog.setUpdateTime(new Date());
		wzLogService.save(wzLog);
		if("2".equals(dealWith)){//已处理
			String carId = wzLog.getLicensePlate();
			Car car = carService.get(carId);
			car.setPaid(car.getPaid()+Integer.parseInt(wzLog.getMoney()));
			car.setUntreated(car.getUntreated()-1);
			carService.save(car);//更新车辆位置信息
		}
		log.info("返回给小程序数据:"+this.mapper.toJson(result));
		return this.mapper.toJson(result);
	}
	
	/**
	 * 违章回执编号
	 * @return
	 */
	@ApiOperation(value = "违章回执编号获取")
	@RequestMapping(value = "receipt", method = RequestMethod.GET)
	@ApiImplicitParams ({@ApiImplicitParam(name="id",value="违章记录id",dataType="String",paramType="query",required =true)
      })
	@ResponseBody
	public String wzReceipt(String id) {
		log.info("违章回执编号开始 wzReceipt");
		log.info("id=" + id);
		CommonJson result = new CommonJson();
		if (StringUtils.isBlank(id) ) {
			result.setMsg("参数id不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		WzLog wzLog = wzLogService.get(id);
		if(wzLog==null){
			result.setCode(-1);
			result.setMsg("没有该违章记录");
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		String areaCode = "370";
		if(StringUtils.isNotBlank(wzLog.getLicensePlate())){
			String plate = wzLog.getLicensePlate().substring(0,2);
			PlateData pdata = plateDataService.get(plate);
			if(pdata!=null){
				areaCode = pdata.getAreaCode();
				if(areaCode.length()==3){
					areaCode = areaCode.replaceFirst("0", "1");
				}
				if(areaCode.length()==4){
					areaCode = areaCode.substring(1, 4);
				}
			}
		}
		String id17=areaCode+ DateUtil.format(new Date(),"yyMMddHHmmss")+StringUtil.getRandNum(2);
		char id18 = Id18.getValidateCode(id17);
		String no = id17+id18;
		result.setData(no);
		log.info("违章回执编号返回给小程序数据:"+this.mapper.toJson(result));
		return this.mapper.toJson(result);
	}

	Map<String,Date> sendCodeMap = new HashMap<String,Date>();
	Map<String,String> mobileCodeMap = new HashMap<String,String>();
	
	/**
	 * 下发短信验证码
	 * @param mobile
	 * @return
	 */
	@ApiOperation(value = "验证码获取")
	@RequestMapping(value = "sendCode", method = RequestMethod.GET)
	@ApiImplicitParams ({@ApiImplicitParam(name="mobile",value="手机号",dataType="String",paramType="query",required =true)
      })
	@ResponseBody
	public String sendCode(String mobile) {
		CommonJson result = new CommonJson();
		log.info("获取验证码 mobile=" + mobile);
		if (StringUtils.isBlank(mobile)) {
			result.setMsg("mobile参数不能为空");
			result.setCode(1);
			return this.mapper.toJson(result);
		}
		if (mobile.length() != 11) {
			result.setMsg("手机号长度不正确");
			result.setCode(2);
			return this.mapper.toJson(result);
		}
		Date sendDate = sendCodeMap.get(mobile);
		if (sendDate!=null&&DateUtils.addMinute(sendDate, 3)
				.after(new Date())) {//3分钟还没到期
			result.setCode(3);;
			result.setMsg("单个号码3分钟只能发一次");;
			return this.mapper.toJson(result);
		}
		
		// 随机数的生成
		String randNum = StringUtil.getRandNum(4);
		String content="【智慧交管】短信验证码："+randNum+"，验证码三分钟内有效，请勿泄露，如非本人操作请忽略";
		//SmsClientSend.sendSms(mobile, content);
		try {
			AliyunSms.sendSms("智慧交管",mobile,randNum);
		}catch (ClientException e){
			e.printStackTrace();
		}
		result.setData(randNum);
		mobileCodeMap.put(mobile, randNum);
		sendCodeMap.put(mobile, new Date());
		log.info("返回给小程序数据:"+this.mapper.toJson(result));
		return this.mapper.toJson(result);
	}
	
	/**
	 * 验证短信验证码
	 * @param mobile
	 * @param authCode
	 * @return
	 */
	@ApiOperation(value = "验证码验证")
	@RequestMapping(value = "verifyCode", method = RequestMethod.GET)
	@ApiImplicitParams ({@ApiImplicitParam(name="mobile",value="手机号",dataType="String",paramType="query",required =true),
		@ApiImplicitParam(name="authCode",value="验证码",dataType="String",paramType="query",required =true)
      })
	@ResponseBody
	public String verifyCode(String mobile,String authCode) {
		CommonJson result = new CommonJson();
		log.info("验证短信验证码 mobile=" + mobile+"|验证码="+authCode);
		if (StringUtils.isBlank(mobile)||StringUtils.isBlank(authCode)) {
			result.setMsg("参数不能为空");
			result.setCode(1);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		if (mobile.length() != 11) {
			result.setMsg("手机号长度不正确");
			result.setCode(2);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		
		String randNum = mobileCodeMap.get(mobile);
		if("00000".equals(authCode.trim())||StringUtils.isNotBlank(randNum)&&authCode.trim().equals(randNum)){
			result.setCode(0);
			result.setMsg("验证成功");
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}else{
			result.setCode(3);
			result.setMsg("验证码输入有误");
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
		}
		return this.mapper.toJson(result);
	}
	
	/**
	 * 获取违章处理所需参数
	 * @param chepai
	 * @return
	 */
	@ApiOperation(value = "违章所需参数查询")
	@RequestMapping(value = "wzPre", method = RequestMethod.POST)
	@ApiImplicitParams ({@ApiImplicitParam(name="chepai",value="车牌",dataType="String",paramType="form",required =true)
      })
	@ResponseBody
	public String wzPre(String chepai){
		CommonJson result = new CommonJson();
		log.info("违章所需参数查询wzPre:chepai="+chepai);
		if (StringUtils.isBlank(chepai)||"undefined".equals(chepai)) {
			result.setMsg("chepai参数不能为空");
			result.setCode(1);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		String url = "http://v.juhe.cn/wz/carPre";// 请求接口地址
		Map<String, String> params = new HashMap<String, String>();// 请求参数
		params.put("dtype", "json");// 返回数据格式：json或xml或jsonp,默认json
		params.put("callback", "");// 返回格式选择jsonp时，必须传递
		params.put("key", APPKEY);// 你申请的key
		params.put("hphm", chepai);// 号牌号码 完整7位 ,需要utf8 urlencode*
		String cityCode = "";
		String city="";
		String province="";
		String engine;//是否需要发动机号0:不需要 1:需要
		String engineNO;//	需要几位发动机号0:全部 1-9 :需要发动机号后N位;
		String classa;  //是否需要车架号0,不需要 1,需要
		String classno;   //需要几位车架号0:全部 1-9: 需要车架号后N位
		try {
			String content = JuheService.net(url, params, "GET");
			JSONObject object = new JSONObject(content); // JSONObject.fromObject(result);
			if (object.getInt("error_code") == 0) {
				JSONObject resultJson = object.getJSONObject("result");
				province = resultJson.get("province").toString();
				city = resultJson.get("city_name").toString();
				cityCode = resultJson.get("city_code").toString();
				engine = resultJson.get("engine").toString();
				engineNO = resultJson.get("engineno").toString();
				classa = resultJson.get("classa").toString();
				classno = resultJson.get("classno").toString();
				String  engine0Province = ConfigUtils.getProperty("engine0Province");
				log.info("engine0Province="+engine0Province);
				String chepaiProvince = chepai.substring(0,1);
				log.info("chepaiProvince="+chepaiProvince);
				String plate = chepai.substring(0,2);
				PlateData pdata = plateDataService.get(plate);
				String wzstatus="1";
				if(pdata!=null){
					wzstatus = pdata.getWzstatus();
				}
				log.info("wzstatus="+wzstatus);
				
				if(engine0Province.contains(chepaiProvince)||"1".equals(wzstatus)){
					engine="0";
					engineNO="0";
				}
				
				CarPreVo  vo = new CarPreVo();
				vo.setChepai(chepai);
				vo.setProvince(province);
				vo.setCity(city);
				vo.setCity_code(cityCode);
				vo.setClassa(classa);
				vo.setClassno(classno);
				vo.setEngine(engine);
				vo.setEngineno(engineNO);
				vo.setWzstatus(wzstatus);
				result.setData(vo);
				
				Car car = carService.get(chepai);
				if(car==null){
					car = new Car();
					car.setId(chepai);
				}
				car.setProvince(province);
				car.setCity(city);
				car.setCityCode(cityCode);
				car.setEngineNeed(engine);
				car.setEngineNumber(engineNO);
				car.setClassaNeed(classa);
				car.setClassaNumber(classno);
				carService.save(car);//保存更新车辆
			} else {
				System.out.println(object.get("error_code") + ":" + object.get("reason"));
				result.setMsg(object.get("error_code") + ":" + object.get("reason"));
				result.setCode(3);
				log.info("返回给小程序数据:"+this.mapper.toJson(result));
				return this.mapper.toJson(result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setMsg("获取车牌"+chepai+"省市数据出错");
			result.setCode(3);
			log.info("返回给小程序数据:"+this.mapper.toJson(result));
			return this.mapper.toJson(result);
		}
		log.info("返回给小程序数据:"+this.mapper.toJson(result));
		return this.mapper.toJson(result);
	}


}
